﻿using MediatR;
using SystemWFH.API.Application.Command.WorkshopCommand;
using SystemWFH.API.DTO;
using SystemWFH.Domain;
using SystemWFH.Infrstructer.Interface;

namespace SystemWFH.API.Application.CommandHandlers.WorkshopCommandHandler
{
    public class WorkshopGetAllCommandHandler : IRequestHandler<WorkshopGetAllCommand, PageDTO<Workshop>>
    {
        private readonly IWorkshopRepository workshopRepository;
        public WorkshopGetAllCommandHandler(IWorkshopRepository workshopRepository)
        {
            this.workshopRepository = workshopRepository;
        }
        public async Task<PageDTO<Workshop>> Handle(WorkshopGetAllCommand request, CancellationToken cancellationToken)
        {
            PageDTO<Workshop> page = new PageDTO<Workshop>();
            var list = await workshopRepository.GetAllAsync();
            list = list.Where(x => x.IsDelete == false).ToList();
            if (!string.IsNullOrEmpty(request.workshopName))
            {
                list = list.Where(x => x.workshopName.Contains(request.workshopName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.workshopNo))
            {
                list = list.Where(x => x.workshopNo.Contains(request.workshopNo)).ToList();
            }
            if (request.workshopState > 0)
            {
                list = list.Where(x => x.workshopState == request.workshopState).ToList();
            }
            page.listCount = list.Count;
            page.pageCount = (int)Math.Ceiling(page.listCount * 1.0 / request.pageSize);
            page.pageList = list.OrderByDescending(x => x.workshopId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            return page;
        }
    }
}
